package jindu.zzh.gj.jinduriddle.riddle.view;

import android.graphics.Typeface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.ant.liao.GifView;
import com.iflytek.cloud.SpeechError;
import com.tmall.ultraviewpager.UltraViewPager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import jindu.zzh.gj.jinduriddle.R;
import jindu.zzh.gj.jinduriddle.riddle.Myapplication;
import jindu.zzh.gj.jinduriddle.riddle.adapter.FragmentAdapter;
import jindu.zzh.gj.jinduriddle.riddle.aiui.IseUtils;
import jindu.zzh.gj.jinduriddle.riddle.aiui.SpeakHandler;
import jindu.zzh.gj.jinduriddle.riddle.aiui.TTSUtils;
import jindu.zzh.gj.jinduriddle.riddle.entity.RiddleBean;


public class MainRiddleActivity extends BaseAcitivity {
    public GifView speechView;
    private TextView tv_countdown;
    private CountDownTimer countDownTimer;
    private UltraViewPager ultraViewPager;
    private UltraViewPager.Orientation gravity_indicator;
    private List<RiddleBean> riddleLists = new ArrayList<>();
    private int curpos = 0;
    private FragmentAdapter fragmentAdapter;
    private List<Fragment> fragmentLists = new ArrayList<>();
    public Typeface tfXingKai;

    //消费滑动事件
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return true;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_riddle_main);
        initDatas();
        initView();
        //requestPermissions();
        TTSUtils.getInstance(this); //初始化语音合成
        IseUtils.getInstance(this); //初始化语音评测
    }

    private void initDatas() {
        fragmentLists = Myapplication.fragments;
        Collections.shuffle(fragmentLists); //打乱集合
        fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), fragmentLists);

    }

    private void initView() {

        // tfXingKai= Typeface.createFromAsset(getAssets(), "fonts/STXINGKA.ttf");
        tfXingKai = Typeface.createFromAsset(getAssets(), "fonts/SIMKAI.TTF");
        speechView = findViewById(R.id.gifView);
        speechView.setGifImage(R.mipmap.speech);
        speechView.setVisibility(View.INVISIBLE);
        // speechView.setShowDimension(60, 60);
        tv_countdown = findViewById(R.id.tv_countdown);
        //倒计时
//        countDownTimer = new CountDownTimer(10000, 1000) {
//            @Override
//            public void onTick(long millisUntilFinished) {
//                // Log.d("TAG", "onTick: " + millisUntilFinished);
//                tv_countdown.setText((millisUntilFinished / 1000) + "");
//            }
//
//            @Override
//            public void onFinish() {
//                Log.d("TAG", "Myapplication.error: " + ReemanApp.error);
//                speechView.setVisibility(View.INVISIBLE);
//                tv_countdown.setText("0");
//                ToastUtils.getInstance(getApplicationContext()).showShortToast("时间到");
//                IseUtils.getInstance(MainRiddleActivity.this).cancelEvaluating();
//                if (ReemanApp.error == 0) {
//                    ++ReemanApp.error;
//                    TTSUtils.getInstance(MainRiddleActivity.this).startSpeak("这句你忘了吗？那我再来一题吧", new SpeakHandler() {
//                        @Override
//                        public void onSpeakBegin() {
//
//                        }
//
//                        @Override
//                        public void onCompleted(SpeechError var1) {
//                            reset();
//                            //再来一次
//                            ultraViewPager.scrollNextPage();
//
//                        }
//                    });
//
//                } else {
//                    //错误过一次了，游戏结束
//                    TTSUtils.getInstance(MainRiddleActivity.this).startSpeak("哎呀，好遗憾，改天再见。", null);
//                    startActivity(new Intent(MainRiddleActivity.this, OverActivity.class));
//                    MainRiddleActivity.this.finish();
//                }
//            }
//        };

        ultraViewPager = findViewById(R.id.ultra_viewpager);
        ultraViewPager.setScrollMode(UltraViewPager.ScrollMode.HORIZONTAL);
        ultraViewPager.setAdapter(fragmentAdapter);
        ultraViewPager.setInfiniteRatio(100);
        ultraViewPager.setInfiniteLoop(true);
        gravity_indicator = UltraViewPager.Orientation.HORIZONTAL;

        ultraViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                // Log.d("TAG", "onPageScrolled: "+position+"...."+positionOffsetPixels);

            }

            @Override
            public void onPageSelected(int position) {
                if (fragmentLists != null) {
                    curpos = position % fragmentLists.size();
                    ((PagerFragment) fragmentLists.get(curpos)).speak(new SpeakHandler() {
                        @Override
                        public void onSpeakBegin() {

                        }

                        @Override
                        public void onCompleted(SpeechError var1) {
                            ((PagerFragment) fragmentLists.get(curpos)).startIseEvaluating();
                        }
                    });
                    Log.e("TAG", "position:" + position + "  curpos: " + curpos + " cutdownView" + (countDownTimer == null));
                    startCountDown();
                }


            }

            @Override
            public void onPageScrollStateChanged(int state) {
                Log.d("TAG", "onPageScrollStateChanged: " + state);
            }
        });
        ultraViewPager.setCurrentItem(400);
        ultraViewPager.post(new Runnable() {
            @Override
            public void run() {
                ((PagerFragment) fragmentLists.get(curpos)).speak(new SpeakHandler() {
                    @Override
                    public void onSpeakBegin() {

                    }

                    @Override
                    public void onCompleted(SpeechError var1) {
                        ((PagerFragment) fragmentLists.get(curpos)).startIseEvaluating();
                    }
                });
                // startCountDown();

            }
        });

    }

    //开始计时
    public void startCountDown() {
        Log.d("TAG", "startCountDown: ");
        if (countDownTimer != null) {
            countDownTimer.start();
        }
    }

    //计时取消
    public void cancelCountDown() {
        Log.d("TAG", "cancelCountDown: ");
        if (countDownTimer != null)
            countDownTimer.cancel();
    }


    public void changeNext(View view) {
        ++Myapplication.currentConut;
        reset();
        ultraViewPager.scrollNextPage();
    }

    //重置倒计时和评测状态
    public void reset() {
        cancelCountDown();
        //tv_countdown.setText("10");
        IseUtils.getInstance(this).cancelEvaluating();
        speechView.setVisibility(View.INVISIBLE);
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        reset();
        TTSUtils.getInstance(this).stopSpeak();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        reset();
    }

//    @SuppressLint("CheckResult")
//    private void requestPermissions() {
//        RxPermissions rxPermission = new RxPermissions(this);
//        rxPermission
//                .requestEach(
//                        Manifest.permission.RECORD_AUDIO)
//                .subscribe(new Consumer<Permission>() {
//                    @Override
//                    public void accept(Permission permission) throws Exception {
//                        if (permission.granted) {
//                            // 用户已经同意该权限
//                            Log.d("TAG", permission.name + " is granted.");
//                        } else if (permission.shouldShowRequestPermissionRationale) {
//                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
//                            Log.d("TAG", permission.name + " is denied. More info should be provided.");
//                        } else {
//                            // 用户拒绝了该权限，并且选中『不再询问』
//                            Log.d("TAG", permission.name + " is denied.");
//                        }
//                    }
//                });
//    }
}
